package net.xdclass.mq;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.request.OrderMessage;
import net.xdclass.service.ProductOrderService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Classname OrderMqListener
 * @Description TODO
 * @Date 2022/5/24 18:01
 * @Created by sunhao
 */
@Slf4j
@Component
@RabbitListener(queues = "${mqconfig.order_release_queue}")
public class OrderMqListener {

  @Autowired
  private ProductOrderService productOrderService;

  /**
   * 超时关单
   * @param orderMessage
   * @param message
   * @param channel
   * @throws IOException
   */
  @RabbitHandler
  public void releaseOrder(OrderMessage orderMessage, Message message, Channel channel) throws IOException {
    long deliveryTag = message.getMessageProperties().getDeliveryTag();
    boolean flag = productOrderService.releaseOrder(orderMessage.getOrderId());
    if (flag) {
      channel.basicAck(deliveryTag, false);
    } else {
      channel.basicReject(deliveryTag, true);
    }
  }
}
